﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using SmoLiteApi.Sql;
using System.Data.SqlClient;
using SmoLiteApi.Helper;

namespace SmoLiteApi
{
    /// <summary/>
    public class UserCollection : IEnumerable<User>
    {
        private Database _database;

        /// <summary/>
        internal UserCollection(Database database)
        {
            this._database = database;
        }

        /// <summary/>
        public User this[string name]
        {
            get
            {
                // get the list
                List<User> users = this.FetchObjects(name);

                // return the data
                if (users.Count == 0)
                {
                    return null;
                }

                // return the one and only
                return users[0];
            }
        }

        /// <summary/>
        public IEnumerator<User> GetEnumerator()
        {
            return this.FetchObjects(null).GetEnumerator();
        }

        /// <summary/>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.FetchObjects(null).GetEnumerator();
        }

        /// <summary/>
        private List<User> FetchObjects(string name)
        {
            List<User> users = new List<User>();

            UserSelectSql userSelectSql = new UserSelectSql();

            // set attributes
            userSelectSql.AddObject(new { Name = name });

            using (SqlCommandHelper sqlCommandHelper = SqlCommandHelper.FetchSqlCommand(this._database.SqlConnection, userSelectSql.Render()))
            {
                using (SqlDataReader sqlDataReader = sqlCommandHelper.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        User user = new User(
                            this._database,
                            sqlDataReader.GetString(sqlDataReader.GetOrdinal(Constant.PARAMETER_NAME)));

                        // add to the list
                        users.Add(user);
                    }
                }
            }

            // retun the list
            return users;
        }
    }
}
